package qqserver.service;

import qqcommon.Message;
import qqcommon.MessageType;
import utility.Utility;

import java.io.IOException;
import java.io.ObjectOutputStream;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.HashMap;
import java.util.Iterator;

/**
 * @author 王艺锡
 * @version 1.0
 * 该类用于服务端向所有在线的用户推送消息
 */
public class SendNews implements Runnable{

    @Override
    public void run() {
        while (true){

            System.out.print("请输入服务端要推送的新闻/消息(退出推送服务:exit):");
            String news = Utility.readString(1000);
            if(news.equals("exit")){
                System.out.println("服务器推送服务已退出!");
                break;
            }
            //获取时间
            LocalDateTime date = LocalDateTime.now();
            DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
            String format = dateTimeFormatter.format(date);

            //设置消息属性
            Message message = new Message();
            message.setSender("服务器");
            message.setMesType(MessageType.MESSAGE_MASS_MES);
            message.setContent(news);
            message.setSendTime(format);

            HashMap<String, ServerConnectClientThread> hm = ManageServerConnectClientThread.getHm();
            Iterator<String> iterator = hm.keySet().iterator();

            //遍历集合，给所有在线用户推送消息
            while (iterator.hasNext()) {
                String userId = iterator.next();

                try {
                    ObjectOutputStream oos =
                            new ObjectOutputStream(ManageServerConnectClientThread
                                    .getServerConnectClientThread(userId)
                                    .getSocket()
                                    .getOutputStream());

                    oos.writeObject(message);

                } catch (IOException e) {
                    e.printStackTrace();
                }


            }

        }


    }
}
